<?php

class Model_HmArticle extends Zend_Db_Table_Abstract
{
	protected $_name = 'hm_article';
	protected $_primary = 'id';
	protected $_sequence = true;
	protected $_dependentTables = array('Model_HmArticleCategory', 'Model_HmArticleTags');
	
	public function getAll()
	{
		if(FW_MODE == 'client') {
			$row = $this->fetchAll($this->select()->where('active = "Y"'));
		} else {
			$row = $this->fetchAll();
		}
		if(!$row) {
			throw new Exception('Could not fetch records.');
		}
		return $row->toArray();
	}
	
	public function getRow($id)
	{
		if(FW_MODE == 'client') {
			$row = $this->fetchRow('active = "Y" AND id = ' . (int)$id);
		} else {
			$row = $this->fetchRow('id = ' . (int)$id);
		}
		if (!$row) {
			throw new Exception('Could not find row $id');
		}
		return $row->toArray();
	}
	
	public function getLast($order, $limit)
	{
		$row = $this->fetchAll($this->select()
											->where('active = "Y"')
											->order($order .' DESC')
											->limit((int)$limit));		
		if(!$row) {
			throw new Exception('Could not fetch last record.');
		}
		return $row->toArray();
	}
	
	public function getHighlight($order, $limit)
	{
		$row = $this->fetchAll($this->select()
											->where('active = "Y" AND highlight = "Y"')
											->order($order .' DESC')
											->limit((int)$limit));		
		if(!$row) {
			throw new Exception('Could not fetch last record.');
		}
		return $row->toArray();
	}
	
	public function addRow($data)
	{
		$row = $this->createRow($data);
		$row->save();
	}
	
	public function updateRow($id, $data)
	{
		$where = 'id = '.(int)$id;
		$row = $this->update($data, $where);
		if(!$row) {
			throw new Exception('Could not update row '.(int)$id);
		}
		return true;
	}
	
	public function deleteRow($id)
	{
		$where = 'id = '.(int)$id;
		$row = $this->delete($where);
		if(!$row) {
			throw new Exception('Could not delete row '.(int)$id);
		}
		return true;
	}
	
	public function assignVisit($id)
	{
		$row = $this->getRow((int)$id);
		$data = array('views'=>$row['views'] + 1);
		$update = $this->updateRow((int)$id, $data);
	}
}